<template>
  <div class="event-detail">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">活动详情</span>
      </template>
    </el-page-header>

    <div v-loading="loading" class="content">
      <el-row :gutter="20">
        <!-- 主要内容 -->
        <el-col :span="16">
          <!-- 基本信息 -->
          <el-card class="info-card">
            <template #header>
              <span class="card-title">基本信息</span>
            </template>
            
            <div class="event-header">
              <el-image 
                :src="event.coverImage || '/default-event.png'" 
                fit="cover"
                class="cover"
              />
              <div class="header-info">
                <h2>{{ event.title }}</h2>
                <div class="meta">
                  <el-tag :type="getStatusType(event.status)">{{ getStatusText(event.status) }}</el-tag>
                  <span class="ml-2 text-muted">ID: {{ event.id }}</span>
                </div>
              </div>
            </div>

            <el-descriptions :column="2" border class="mt-4">
              <el-descriptions-item label="活动时间" :span="2">
                {{ formatDateTime(event.startTime) }} 至 {{ formatDateTime(event.endTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="报名截止">
                {{ formatDateTime(event.registrationDeadline) }}
              </el-descriptions-item>
              <el-descriptions-item label="活动地点">
                {{ event.location || '待定' }}
              </el-descriptions-item>
              <el-descriptions-item label="参与人数">
                {{ event.currentParticipants || 0 }} / {{ event.maxParticipants || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="候补人数">
                {{ event.waitlistCount || 0 }}
              </el-descriptions-item>
              <el-descriptions-item label="技能要求">
                {{ event.skillLevel || '不限' }}
              </el-descriptions-item>
              <el-descriptions-item label="费用">
                {{ event.fee ? `¥${event.fee}` : '免费' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建者ID">
                {{ event.creatorId }}
              </el-descriptions-item>
              <el-descriptions-item label="俱乐部ID">
                {{ event.clubId || '无' }}
              </el-descriptions-item>
              <el-descriptions-item label="创建时间" :span="2">
                {{ formatDate(event.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="活动描述" :span="2">
                <div class="description">{{ event.description || '暂无描述' }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 参与者列表 -->
          <el-card class="participants-card mt-3">
            <template #header>
              <div class="card-header">
                <span class="card-title">参与者列表</span>
                <el-space>
                  <el-radio-group v-model="participantFilter" size="small">
                    <el-radio-button label="all">全部</el-radio-button>
                    <el-radio-button label="confirmed">已确认</el-radio-button>
                    <el-radio-button label="pending">待确认</el-radio-button>
                    <el-radio-button label="waitlist">候补</el-radio-button>
                  </el-radio-group>
                </el-space>
              </div>
            </template>

            <el-table :data="filteredParticipants" stripe max-height="500">
              <el-table-column prop="userId" label="用户ID" width="100" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getParticipantStatusType(row.status)">
                    {{ getParticipantStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="是否候补" width="100">
                <template #default="{ row }">
                  <el-tag v-if="row.isWaitlist" type="warning">候补</el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column label="签到状态" width="100">
                <template #default="{ row }">
                  <el-tag v-if="row.checkedIn" type="success">已签到</el-tag>
                  <el-tag v-else type="info">未签到</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="signupNote" label="报名备注" min-width="150" show-overflow-tooltip />
              <el-table-column prop="createdAt" label="报名时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button 
                    v-if="row.status === 'pending'" 
                    link 
                    type="success" 
                    size="small" 
                    @click="approveSignup(row.id)"
                  >
                    通过
                  </el-button>
                  <el-button 
                    v-if="row.status === 'pending'" 
                    link 
                    type="danger" 
                    size="small" 
                    @click="rejectSignup(row.id)"
                  >
                    拒绝
                  </el-button>
                  <el-button 
                    v-if="!row.checkedIn && event.status === 'ongoing'" 
                    link 
                    type="primary" 
                    size="small" 
                    @click="checkIn(row.id)"
                  >
                    签到
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 候补转正按钮 -->
            <div v-if="waitlistCount > 0" class="mt-3">
              <el-button type="primary" @click="promoteWaitlist">
                候补转正 ({{ waitlistCount }}人)
              </el-button>
            </div>
          </el-card>
        </el-col>

        <!-- 侧边栏 -->
        <el-col :span="8">
          <!-- 快速操作 -->
          <el-card class="action-card">
            <template #header>
              <span class="card-title">快速操作</span>
            </template>
            <el-space direction="vertical" :size="12" style="width: 100%">
              <el-button 
                v-if="event.status === 'upcoming'" 
                type="warning" 
                style="width: 100%" 
                @click="cancelEvent"
              >
                取消活动
              </el-button>
              <el-button 
                type="danger" 
                style="width: 100%" 
                @click="deleteEvent"
              >
                删除活动
              </el-button>
              <el-button 
                style="width: 100%" 
                @click="exportParticipants"
              >
                导出参与者
              </el-button>
            </el-space>
          </el-card>

          <!-- 统计信息 -->
          <el-card class="stats-card mt-3">
            <template #header>
              <span class="card-title">统计信息</span>
            </template>
            <div class="stat-item">
              <span class="stat-label">已确认</span>
              <span class="stat-value">{{ confirmedCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">待确认</span>
              <span class="stat-value">{{ pendingCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">候补中</span>
              <span class="stat-value">{{ waitlistCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">已签到</span>
              <span class="stat-value">{{ checkedInCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">报名率</span>
              <span class="stat-value">{{ signupRate }}%</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { eventApi } from '@/api/event'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const event = ref({})
const participants = ref([])
const participantFilter = ref('all')

const eventId = computed(() => route.params.id)

const filteredParticipants = computed(() => {
  if (participantFilter.value === 'all') return participants.value
  if (participantFilter.value === 'waitlist') {
    return participants.value.filter(p => p.isWaitlist)
  }
  return participants.value.filter(p => p.status === participantFilter.value)
})

const confirmedCount = computed(() => 
  participants.value.filter(p => p.status === 'confirmed').length
)

const pendingCount = computed(() => 
  participants.value.filter(p => p.status === 'pending').length
)

const waitlistCount = computed(() => 
  participants.value.filter(p => p.isWaitlist).length
)

const checkedInCount = computed(() => 
  participants.value.filter(p => p.checkedIn).length
)

const signupRate = computed(() => {
  const max = event.value.maxParticipants || 1
  const current = event.value.currentParticipants || 0
  return Math.round((current / max) * 100)
})

onMounted(() => {
  loadEventDetail()
  loadParticipants()
})

const loadEventDetail = async () => {
  loading.value = true
  try {
    event.value = await eventApi.getEventDetail(eventId.value)
  } catch (error) {
    console.error('加载活动详情失败:', error)
    ElMessage.error('加载活动详情失败')
  } finally {
    loading.value = false
  }
}

const loadParticipants = async () => {
  try {
    participants.value = await eventApi.getEventParticipants(eventId.value)
  } catch (error) {
    console.error('加载参与者列表失败:', error)
  }
}

const cancelEvent = () => {
  ElMessageBox.prompt('请输入取消原因', '取消活动', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'textarea'
  }).then(async ({ value }) => {
    try {
      await eventApi.cancelEvent(eventId.value, value)
      ElMessage.success('活动已取消')
      loadEventDetail()
    } catch (error) {
      console.error('操作失败:', error)
    }
  }).catch(() => {})
}

const deleteEvent = () => {
  ElMessageBox.confirm('确定要删除该活动吗？此操作不可恢复', '警告', {
    type: 'error'
  }).then(async () => {
    try {
      await eventApi.deleteEvent(eventId.value)
      ElMessage.success('删除成功')
      router.push('/events')
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

const approveSignup = async (signupId) => {
  try {
    await eventApi.approveSignup(signupId, true)
    ElMessage.success('已通过')
    loadParticipants()
    loadEventDetail()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const rejectSignup = async (signupId) => {
  try {
    await eventApi.approveSignup(signupId, false)
    ElMessage.success('已拒绝')
    loadParticipants()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const checkIn = async (signupId) => {
  try {
    // TODO: 实现签到功能
    ElMessage.success('签到成功')
    loadParticipants()
  } catch (error) {
    console.error('签到失败:', error)
  }
}

const promoteWaitlist = async () => {
  try {
    const result = await eventApi.promoteFromWaitlist(eventId.value)
    ElMessage.success(`成功转正 ${result} 人`)
    loadParticipants()
    loadEventDetail()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const exportParticipants = () => {
  ElMessage.info('导出功能开发中')
}

const goBack = () => {
  router.back()
}

const getStatusType = (status) => {
  const types = { upcoming: 'primary', ongoing: 'success', completed: 'info', cancelled: 'danger' }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = { upcoming: '待开始', ongoing: '进行中', completed: '已结束', cancelled: '已取消' }
  return texts[status] || status
}

const getParticipantStatusType = (status) => {
  const types = { confirmed: 'success', pending: 'warning', cancelled: 'info', attended: 'success', absent: 'danger' }
  return types[status] || ''
}

const getParticipantStatusText = (status) => {
  const texts = { confirmed: '已确认', pending: '待确认', cancelled: '已取消', attended: '已参加', absent: '缺席' }
  return texts[status] || status
}

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const formatDateTime = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-'
}
</script>

<style scoped>
.event-detail {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
}

.event-header {
  display: flex;
  gap: 20px;
}

.cover {
  width: 200px;
  height: 150px;
  border-radius: 8px;
  flex-shrink: 0;
}

.header-info h2 {
  margin: 0 0 12px 0;
  font-size: 24px;
}

.meta {
  display: flex;
  align-items: center;
}

.ml-2 {
  margin-left: 8px;
}

.mt-3 {
  margin-top: 16px;
}

.mt-4 {
  margin-top: 20px;
}

.text-muted {
  color: #909399;
}

.card-title {
  font-weight: 600;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.description {
  line-height: 1.6;
  white-space: pre-wrap;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  color: #606266;
}

.stat-value {
  font-weight: 600;
  color: #303133;
}
</style>

